<?php
namespace app\common\model;

use app\extra\BaseModel;
use app\extra\DBCont;
use think\Exception;

class Visit extends BaseModel
{
    public function addPageView($id, $vote_id){
        $data = [
            'user_id' => getPersonId(),
            'player_id' => $id,
            'vote_id' => $vote_id,
            'visit_time' => strtotime(date('Y-m-d')),
        ];
        $where = [];
        foreach ($data as $key => $item){
            $where[] = [$key, '=', $item];
        }
        $r = $this->where($where)->find();
        if (!empty($r)){
            return true;
        }
        $r = $this->createAdd($data);
        return $r;
    }
    /**
     * 统计某区间的投票活动的访问量数量
     * @param $vote_id
     * @param $startTime
     * @param $endTime
     * @return array|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function statistics($vote_id, $startTime, $endTime){
        $vote = $this->where('vote_id', $vote_id)
            ->whereBetween('visit_time', [$startTime-1, $endTime+1])
            ->field(['visit_time as key', 'count(*) as number'])->group('vote_time')->select();
        return $vote;
    }

    /**
     * 统计某个时间区间的选手的访问总量
     * @param $player_id
     * @param $startTime
     * @param $endTime
     * @return array|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function statisticsPlayer($player_id, $startTime, $endTime){
        $player = $this->where('player_id', $player_id)
            ->whereBetween('visit_time', [$startTime-1, $endTime+1])
            ->field(['visit_time as key', 'count(*) as number'])->group('vote_time')->select();
        return $player;
    }
}